<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/31
 * Time: 17:58
 */

namespace common\helps;
use Yii;

/**
 * Class Upload UEditor 上传处理类
 * @package common\helps
 */
class Upload
{
    public $defaultWater;
    public $info = [
        'fileName' => '',//文件名
        'oriName' => '',//原文件名
        'dir' => '',//目录
        'path' => '',//完整路径
        'size' => '',//文件大小
        'ext' => '',//文件后缀
        'url' => '',//
    ];
    public $config = [
        'dir' => '', //目录
        'size' => 1024 * 1024 * 3,//限制大小
        'allowExt' => '.png, .jpg, .jpeg, .gif',//允许文件类型
        'isCover' => false,//是否覆盖
        'filePath' => '',//自定义文件路径
        'rule' => '',//文件规则
        'maxLength' => 0,//图片最长边限制
    ];

    private $errorCode = 0;
    private $errorInfo = '';

    public function __construct($config)
    {
        foreach ($config as $key => $value) {
            $this->setOption($key, $value);
        }
    }

    /**
     * 设置配置
     * @param $key
     * @param $value
     * @return bool
     */
    public function setOption($key, $value)
    {
        if (isset($this->config[$key])) {
            $this->config[$key] = $value;
            return true;
        } else {
            return false;
        }
    }

    /**
     *上传文件
     * @param $key
     * @return array
     */
    public function uploadOne($key)
    {
        try {

            if (!isset($_FILES[$key]) || !$_FILES[$key])
            {
                return $this->setError('上传文件不存在', 2);
            }
            $file = $_FILES[$key];
            switch($file['error'])
            {
                case 0:break;
                case 1:return $this->setError('文件大小超出了服务器的限制', 3);break;
                case 2:return $this->setError('文件大小超出浏览器限制', 4);break;
                case 3:return $this->setError('文件仅部分被上传', 5);break;
                case 4:return $this->setError('没有找到要上传的文件', 6);break;
                case 6:return $this->setError('没有找到临时文件夹', 7);break;
                case 7:return $this->setError('文件写入失败', 8);break;
                case 8:return $this->setError('文件上传被停止', 9);break;
                default:
                    return $this->setError('异常', 9);
                    break;
            }

            if($this->config['size'] > 0 && $file['size'] > $this->config['size'])
            {
                return $this->setError('文件大小超出配置限制', 10);
            }
            if(!$this->config['dir'])
            {
                return $this->setError('上传根目录不存在', 11);
            }

            $this->info['oriName'] = $file['name'];
            $this->info['ext'] = pathinfo($file['name'], PATHINFO_EXTENSION);

            if(in_array($this->info['ext'], $this->config['allowExt']))
            {
                return $this->setError('该文件类型不允许上传');
            }
            if($this->config['rule'])
            {
                $this->info['path'] = Func::getPath($this->config['rule'], Yii::getAlias('@webroot')).'.'.$this->info['ext'];
            }
            else
            {
                $this->info['path'] = $this->config['dir'].'/'.time().rand(10000, 99999).'.'.$this->info['ext'];
            }
            $this->info['url'] = str_replace($this->config['dir'], '', $this->info['path']);
            $this->info['dir'] = dirname($this->info['path']);
            $this->info['fileName'] = pathinfo($this->info['path'], PATHINFO_FILENAME);

            if(!is_dir($this->info['dir']))
            {
                if(!Func::mkdir($this->info['dir'], 0755))
                {
                    return $this->setError('创建目录失败', 12);
                }
            }

            if(!is_writable($this->info['dir']))
            {
                return $this->setError('上传目录没有写入权限', 13);
            }

            if(!$this->config['isCover']){
                $this->info['path'] = $this->checkUnique($this->info['path']);
            }
            if(strpos(strtolower($file['type']), 'image') !== false)
            {
                if($this->handlingImage($file))
                {
                    $this->info['size'] = filesize($this->info['path']);
                    return array_merge($this->info, ['status'=>true]);
                }
                else
                {
                    return $this->setError('图片处理失败', 15);
                }

            }
            else
            {
                if(move_uploaded_file($file['tmp_name'], $this->info['path']))
                {
                    $this->info['size'] = filesize($this->info['path']);
                    return array_merge($this->info, ['status'=>true]);
                }
                else
                {
                    return $this->setError('保存文件失败', 14);
                }
            }

        }
        catch (\Exception $e)
        {
            return $this->setError($e->getMessage(), $e->getCode());
        }
    }

    public function checkUnique($path)
    {
        while(file_exists($path))
        {
            if($this->config['rule'])
            {
                $path = Func::getPath($this->config['dir'], Yii::getAlias('@webroot'));
            }
            else
            {
                $path .= dirname($path).'/'.pathinfo($path, PATHINFO_FILENAME).rand(0, 9).'.'.pathinfo($path.PATHINFO_EXTENSION);
            }
        }

        return $path;
    }

    /**
     * 图像处理
     * @param $file
     * @return bool
     */
    public function handlingImage($file)
    {
        $ImageClass = "\\common\\helps\\Image";
        if(class_exists($ImageClass))
        {
            $config = [
                'savePath'=>$this->info['path'],//保存路径
                'maxWidth'=>800,
                'water'=>$this->defaultWater,
                'waterPosition'=>$ImageClass::WATER_RIGHT_DOWN,//水印位置
                'fillColor'=>'',
                'fontFile'=>\Yii::getAlias('@webroot').'/font/msyh.ttf',
            ];
            /** @var \common\helps\Image $Image */
            $Image  = new $ImageClass($config);
            $image = $Image->autoImage($file['tmp_name']);
            return $Image->save($image);
        }
        else
        {


            if(move_uploaded_file($file['tmp_name'], $this->info['path']))
            {
                return true;
            }
            return false;
        }
    }



    /**
     * 设置错误
     * @param $msg
     * @param $code
     * @return array
     */
    public function setError($msg, $code = 1)
    {
        $this->errorInfo = $msg;
        $this->errorCode = $code;
        return [
            'status'=>false,
            'errorCode'=>$code,
            'errorInfo'=>$msg,
        ];
    }

    /**
     * 获取错误信息
     * @return array
     */
    public function getError()
    {
        return [
            'errorCode'=>$this->errorCode,
            'errorInfo'=>$this->errorInfo,
        ];
    }


    /**
     * 多文件上传
     * @param array $keys
     * @return array
     */
    public function uploadMore($keys = [])
    {
        $result = [];
        foreach($_FILES as $key => $value)
        {
            if(!$keys || in_array($key, $keys))
            {
                continue;
            }
            $result[] = $this->uploadOne($key);
        }
        return $result;
    }

    /**
     * @return string
     */
    public function getErrorInfo()
    {
        return $this->errorInfo;
    }


}
